#include "paths.hpp"

using namespace std;

paths::paths() :

        m_fullpath(""),
        m_path(""),
        m_fullfilename(""),
        m_filename(""),
        m_extension(""),
        m_directory(false),
        m_file(false),
        m_exists(false),
        sep('/')

{
    m_fullpath = getRootPath();
    m_directory = (whatKindOf() == directory)? true : false;
    m_file = (m_directory)? false : true;
    getLevels();
    extractPath();
    extractFilename();
    extractExtension();

}

paths::paths(std::string path) :

        m_fullpath(path),
        m_path(""),
        m_fullfilename(""),
        m_filename(""),
        m_extension(""),
        m_directory(false),
        m_file(false),
        m_exists(false),
        sep('/')

{
    m_directory = (whatKindOf() == directory)? true : false;
    m_file = (m_directory)? false : true;
    getLevels();
    extractPath();
    extractFilename();
    extractExtension();

}


vector< string > paths::ListFiles(string ipath)
{    
	namespace fs = boost::filesystem;
	fs::path fpath(ipath);	
	vector<string> files;
	if ( !exists( fpath ) ) return files;
	fs::directory_iterator end_itr;	
	for ( fs::directory_iterator itr( fpath ); itr != end_itr; ++itr )	
		files.push_back(itr->path().filename());

	return files;
}


void paths::getLevels()
{
    size_t i = 0;
	for (string::iterator it = m_fullpath.begin(); it < m_fullpath.end(); it++, i++)
    {
        if (*it == sep)
            m_levels.push_back(i);
    }
}


void paths::extractFilename()
{
    assert(!m_fullpath.empty());
    if (m_file == true)
    {
        m_fullfilename = m_fullpath.substr(m_fullpath.find_last_of("/") + 1, m_fullpath.size());
        size_t pos = 0;
        if ((pos = m_fullfilename.find_last_of(".")) != string::npos)
            m_filename = m_fullfilename.substr(0, pos);
    }

}

void paths::extractExtension()
{
    assert(!m_fullpath.empty());
    if (m_file == true)
    {
        assert(!m_fullfilename.empty());
        size_t pos = 0;
        if ((pos = m_fullfilename.find_last_of(".")) != string::npos)
            m_extension = m_fullfilename.substr(pos, m_fullfilename.size());
    }
}

int paths::whatKindOf()
{	
	return (boost::filesystem::is_directory(boost::filesystem::path(m_fullpath))) ? directory : file;
}


const std::string paths::ToString()
{
    stringstream out;
    out << "FULLPATH : " << m_fullpath << endl << "PATH : " << m_path << endl << "FILENAME : "\
    << m_filename << endl << "FULLFILENAME : " << m_fullfilename << endl << "EXTENSION : " << m_extension << endl << "IS DIRECTORY ? " << IsDirectory()\
    << endl << "IS_FILE ? " << IsFile() << endl << "HAS EXTENSION : " << HasExtension() << endl;
    return out.str();
}
